//
//  SEGCommonAllDoorListViewController.m
//  SEGIntelligentHardware
//
//  Created by Clavis on 2019/5/5.
//  Copyright © 2019 Clavis. All rights reserved.
//

#import "SEGCommonAllDoorListViewController.h"
#import "SEGCommonDoorConfigViewController.h"
#import "SEGOpenDoorNoticeChooseViewController.h"
#import "SEGCommonDoorListTableViewCell.h"
#import "SEGNewMyDoorListModel.h"
#import <Commom/UIControl+YYAdd.h>
#import "SEGCommonDoorViewController.h"
#import "SEGOpenDoorBussinessManager.h"
//ViewModel
#import <SEGViewModel/SEGDoorListViewModel.h>

@interface SEGCommonAllDoorListViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray<SEGNewMyDoorListModel *> *allDoorList;
@property (nonatomic, strong) NSArray<SEGNewMyDoorListModel *> *commonDoorList;
@property (nonatomic, assign) BOOL needUpdate;
@property (nonatomic, strong) SEGDoorListViewModel *doorListViewModel;

@end

@implementation SEGCommonAllDoorListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    
    self.title = @"门禁列表";
    [self showCustomNavigationBackButton];
    [self showCustomNavigationRightButtonWithTitle:@"开门提示音" image:nil hightlightImage:nil color:kColor_1];
    self.view.backgroundColor = kColor_W;
    
    // 处理导航层级
    NSMutableArray<UIViewController *> *viewControllers = [NSMutableArray array];
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if (![vc isKindOfClass:[SEGCommonDoorViewController class]]) {
            [viewControllers addObject:vc];
        }
    }
    self.navigationController.viewControllers = [viewControllers copy];
    
    // 请求新的门禁列表
    @weakify(self);
    [SVProgressHUD show];
    [[self.doorListViewModel requestNetAllDoorList] subscribeNext:^(NSArray<SEGNewMyDoorListModel *> * _Nullable doorList) {
        @strongify(self);
        [SVProgressHUD dismiss];
        [self setupUI];
        [self updateUI];
    }];
   
    // 每次进入页面都要提交开门记录
    [self.doorListViewModel submitOpenDoorHistory];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.needUpdate) {
        self.needUpdate = NO;
        [self updateUI];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.needUpdate = YES;
}

- (void)updateUI {
    self.allDoorList = [self.doorListViewModel getLocalAllDoorList];
    self.commonDoorList = [self.doorListViewModel getOldCommonDoor];
    [self.tableView reloadData];
    if (self.allDoorList.count == 0) {
        [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.view,@"text":@"这儿什么门都没有",@"backcolor":kColor_W}];
    }
}

- (void)setupUI {
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = kColor_W;
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.rowHeight = 55;
        [tableView registerClass:[SEGCommonDoorListTableViewCell class] forCellReuseIdentifier:@"SEGCommonDoorListTableViewCell"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:tableView];
        tableView;
    });
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 44, 0));
    }];
    
    
    UIButton *settingButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"设置常用门" forState:UIControlStateNormal];
        [button setTitleColor:kColor_W forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        button.titleLabel.font = kFont_16;
        button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, LYSafeAreaBottom(), 0);
        [self.view addSubview:button];
        button;
    });
    [settingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(44 + LYSafeAreaBottom());
    }];
    WeakSelf;
    [settingButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        SEGCommonDoorConfigViewController *configVC = [[SEGCommonDoorConfigViewController alloc] init];
        [weakSelf.navigationController pushViewController:configVC animated:YES];
    }];
}

#pragma mark - Action
- (void)onNavigationRightButtonClicked:(UIButton *)sender {
    SEGOpenDoorNoticeChooseViewController *VC = [SEGOpenDoorNoticeChooseViewController new];
    VC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)onNavigationLeftButtonClicked:(UIButton *)sender {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        if (self.disapperCallback) {
            self.disapperCallback();
        }
    }];
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource> methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.commonDoorList.count > 0 ? 2 : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.commonDoorList.count > 0) {
        return section == 0 ? self.commonDoorList.count : self.allDoorList.count;
    }
    return self.allDoorList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGCommonDoorListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SEGCommonDoorListTableViewCell" forIndexPath:indexPath];
    SEGNewMyDoorListModel *doorModel = nil;
    if (self.commonDoorList.count > 0 && indexPath.section == 0) {
        doorModel = self.commonDoorList[indexPath.row];
    } else {
        doorModel = self.allDoorList[indexPath.row];
    }
    [cell updateUIWithModel:doorModel];
    cell.openDoorBlock = ^{
        WeakSelf;
        [[SEGOpenDoorBussinessManager shareInstance] openDoorWithDoorModel:doorModel completeCallback:^(SEGNewOpenDoorModel * _Nonnull data) {
            if (weakSelf.completedCallback) {
                weakSelf.completedCallback(data);
            }
        }];
    };
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    
    NSString *text = @"所有门";
    if (self.commonDoorList.count > 0 && section == 0) {
        text = @"常用门";
    }
    UILabel *titleLabel = ({
        UILabel *label = [[UILabel alloc] init];
        [headerView addSubview:label];
        label.textColor = kColor_1;
        label.font = kFont_15;
        label.text = text;
        label;
    });
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 15, 0, 15));
    }];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 58.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

#pragma mark - Getter
- (SEGDoorListViewModel *)doorListViewModel {
    if (!_doorListViewModel) {
        _doorListViewModel = [SEGDoorListViewModel new];
    }
    return _doorListViewModel;
}

@end
